package cc.jq1024.infrastructure.persistent.repository;

import cc.jq1024.domain.task.model.entity.TaskEntity;
import cc.jq1024.domain.task.repository.ITaskRepository;
import cc.jq1024.infrastructure.event.EventPublisher;
import cc.jq1024.infrastructure.persistent.dao.ITaskDao;
import cc.jq1024.infrastructure.persistent.po.TaskPO;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc: 任务服务仓储接口 - 实现
 * @Date: 2024-06-21-15:30
 */
@Repository
public class TaskRepository implements ITaskRepository {

    @Resource
    private ITaskDao taskDao;
    @Resource
    private EventPublisher eventPublisher;

    /**
     * 查询发送MQ失败和超时1分钟未发送的MQ
     *
     * @return 未发送的任务消息列表10条
     */
    @Override
    public List<TaskEntity> queryNoSendMessageTaskList() {
        List<TaskPO> tasks = taskDao.queryNoSendMessageTaskList();
        List<TaskEntity> taskEntities = new ArrayList<>(tasks.size());
        for (TaskPO task : tasks) {
            TaskEntity taskEntity = new TaskEntity();
            taskEntity.setUserId(task.getUserId());
            taskEntity.setTopic(task.getTopic());
            taskEntity.setMessageId(task.getMessageId());
            taskEntity.setMessage(task.getMessage());
            taskEntities.add(taskEntity);
        }
        return taskEntities;
    }

    /**
     * 发送 Task MQ 任务
     * @param taskEntity 任务实体对象
     */
    @Override
    public void sendMessage(TaskEntity taskEntity) {
        eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage());
    }

    /**
     * 发送MQ消息成功
     * @param userId 用户ID
     * @param messageId 消息ID
     */
    @Override
    public void updateTaskSendMessageCompleted(String userId, String messageId) {
        TaskPO taskReq = new TaskPO();
        taskReq.setUserId(userId);
        taskReq.setMessageId(messageId);
        taskDao.updateTaskSendMessageCompleted(taskReq);
    }

    /**
     * 发送MQ消息失败
     * @param userId 用户ID
     * @param messageId 消息ID
     */
    @Override
    public void updateTaskSendMessageFail(String userId, String messageId) {
        TaskPO taskReq = new TaskPO();
        taskReq.setUserId(userId);
        taskReq.setMessageId(messageId);
        taskDao.updateTaskSendMessageFail(taskReq);
    }
}
